package com.sx.iptv.enc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sx.iptv.http.OkHttpExample;
import com.sx.iptv.model.Param;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

public class CryptoUtil {

    private static final Logger logger = LoggerFactory.getLogger(CryptoUtil.class);

    static {
        // 添加Bouncy Castle提供者
        Security.addProvider(new BouncyCastleProvider());
    }

    private static String undress(String a, String b, String c) throws Exception {
        // 密钥和IV需要是字节数组
        byte[] keyBytes = a.getBytes("UTF-8");
        byte[] ivBytes = b.getBytes("UTF-8");
        // 使用AES算法，CBC模式，ZeroPadding填充方式
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        // 解密前需要先对密文进行Base64解码
        byte[] decodedValue = Base64.getDecoder().decode(c);
        // 执行解密操作
        byte[] decryptedBytes = cipher.doFinal(decodedValue);
        // 去除ZeroPadding填充
        int padCount = decryptedBytes[decryptedBytes.length - 1];
        int dataLength = decryptedBytes.length - padCount;
        // 提取实际数据
        byte[] result = new byte[dataLength];
        System.arraycopy(decryptedBytes, 0, result, 0, dataLength);
        return new String(result, "UTF-8");
    }

    public static String getUrl(Param param) {
        try {
            String nlTvInfo = JSON.parseObject(undress(param.getSTV().substring(0,16),param.getSRadio().substring(0,16),param.getSTV().substring(16))).getString("nl");
//            logger.info("Decrypted Data: " + nlTvInfo);
            String playUrl = JSON.parseObject(nlTvInfo).getString("m3u8");
            logger.info("playUrl:{}", playUrl);
            return playUrl;
        } catch (Exception e) {
            logger.error("获取链接异常");
            logger.error(e.getLocalizedMessage(), e);
            return null;
        }
    }
}
